<?php
namespace Lib;
$_CONFIG = array ();

/**
 *
 * @author ximi
 *        
 */
class Config {
	/**
	 *
	 * @var array
	 */
	private $_aData = array ();
	/**
	 *
	 * @param unknown_type $sFile        	
	 * @param unknown_type $bDefault        	
	 * @return boolean
	 */
	public function init($sFile, $bDefault = false) {
		global $_CONFIG;
		if ($bDefault) {
			$sId = 'default';
		} else {
			$sId = $this->_getIdByFile ( $sFile );
		}
		if (is_file ( $sFile )) {
			$this->_aData [$sId] = parse_ini_file ( $sFile, true );
			if ($sId == 'default') {
				$this->_aData ['default'] ['base'] ['self'] = $_SERVER ['PHP_SELF'];
				$_CONFIG = $this->_aData ['default'];
			}
			return true;
		} else {
			return false;
		}
	}
	
	public function get($sName, $sFile = null) {
		$sId = $this->_getIdByFile ( $sFile );
		list ( $sType, $sName ) = explode ( '.', $sName );
		if ($sName) {
			if (is_array ( $this->_aData [$sId] [$sType] )) {
				if (array_key_exists ( $sName, $this->_aData [$sId] [$sType] )) {
					$sValue = $this->_aData [$sId] [$sType] [$sName];
				} else {
					$aParentValue = $this->_aData [$sId] [$sType];
					if (is_array ( $aParentValue )) {
						$sValue = $this->_parseConf ( $aParentValue, $sName );
					}
				}
			}
			if ($sValue === null && $sId != 'default') {
				return $this->get ( $sType . '.' . $sName );
			}
			return $sValue;
		} elseif ($sType) {
			return $this->_aData [$sId] [$sType];
		} else {
			return false;
		}
	}
	
	public function set($sName, $sValue, $sFile = null) {
		if ($sFile) {
			if (is_file ( $sFile )) {
				$sId = md5 ( realpath ( $sFile ) );
			} else {
				$sId = $sFile;
			}
		} else {
			$sId = 'default';
		}
		
		list ( $sType, $sName ) = explode ( '.', $sName );
		$this->_aData [$sId] [$sType] [$sName] = $sValue;
		
		if ($sId == 'default') {
			global $_CONFIG;
			$_CONFIG = $this->_aData ['default'];
		}
	}
	
	private function _getIdByFile($sFile = null) {
		if (is_file ( $sFile )) {
			return md5 ( realpath ( $sFile ) );
		} else {
			return 'default';
		}
	}
	
	private function _parseConf($aValue, $sName) {
		$aResult = null;
		foreach ( $aValue as $sKey => $sRow ) {
			$aMatch = array ();
			if (preg_match ( '/^' . $sName . '_{0,1}(\d+)$/i', $sKey, $aMatch )) {
				$aResult [$aMatch [1]] = $sRow;
			}
		}
		return $aResult;
	}
}

?>